package com.woyou.service.pay;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import net.sourceforge.simcpux.Util;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.util.Log;

import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.woyou.service.pay.PayManger.IPayCallback;

final class WeixinPayImp {

	private static final String TAG = "WeixinPayController";
	public static final String WEIXIN_PAY_ACTION = "com.woyou.weixin.pay";

	IWXAPI msgApi;

	private PayReq req;

	private Map<String, String> resultunifiedorder;

	private IPayCallback callback;
	private String price;
	private String commName;
	private String orderId;

	private Context mContext;

	public WeixinPayImp(Context context) {
		// TODO Auto-generated constructor stub
		if (msgApi == null)
			msgApi = WXAPIFactory.createWXAPI(context, null);
		msgApi.registerApp(PayConfig.WEIXIN_APP_ID);
		if (req == null)
			req = new PayReq();
		this.mContext = context;
		onRegister();
	}

	void onPay(PayManger.IPayCallback callback, String commName, String price, String orderId) {
		// 生成预付单ID
		if (msgApi.isWXAppInstalled() == false) {
			callback.onError(PayConfig.PAY_NOT_CLIENT);
			return;
		}
		this.callback = callback;
		this.commName = commName;
		this.price = price;
		this.orderId = orderId;
		getPrepayId();
	}

	/**
	 * 生成预付单ID
	 */
	public void getPrepayId() {
		GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
		getPrepayId.execute();
	}

	/**
	 * 生成签名参数
	 */
	public void genPayReq() {
		// 公众账号ID
		req.appId = PayConfig.WEIXIN_APP_ID;
		// 商户号
		req.partnerId = PayConfig.WEIXIN_MCH_ID;
		// 预支付交易会话ID
		req.prepayId = resultunifiedorder.get("prepay_id");
		// 扩展字段
		req.packageValue = "Sign=WXPay";
		// 随机字符串
		req.nonceStr = Util.genNonceStr();
		// 时间戳
		req.timeStamp = String.valueOf(Util.genTimeStamp());

		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", req.appId));
		signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
		signParams.add(new BasicNameValuePair("package", req.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

		// 签名
		req.sign = Util.genAppSign(signParams);
		Log.e("orion", signParams.toString());

		// 发送支付请求
		sendPayReq();

	}

	/** 发送支付请求 */
	private void sendPayReq() {
		msgApi.registerApp(PayConfig.WEIXIN_APP_ID);
		msgApi.sendReq(req);
	}

	private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {
		@Override
		protected void onPostExecute(Map<String, String> result) {
			resultunifiedorder = result;
			if (resultunifiedorder.get("return_code").equals("FAIL")) {
				callback.onError(PayConfig.PAY_SIGN_ERROR);
				return;
			}
			// 生成签名参数
			genPayReq();
		}

		@Override
		protected Map<String, String> doInBackground(Void... params) {
			String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
			String entity = genProductArgs();
			Log.e("orion", entity);

			byte[] buf = Util.httpPost(url, entity);
			String content = "";
			if(buf!=null && buf.length>0){
				content = new String(buf);
			}
			Log.e("orion", content);

			Map<String, String> xml = Util.decodeXml(content);

			return xml;
		}

	}

	/** 生成订单的参数 */
	private String genProductArgs() {
		StringBuffer xml = new StringBuffer();

		try {
			String nonceStr = Util.genNonceStr();
			xml.append("</xml>");
			List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			// 公众账号ID
			packageParams.add(new BasicNameValuePair("appid", PayConfig.WEIXIN_APP_ID));
			// 商品描述
			packageParams.add(new BasicNameValuePair("body", "我有外卖订单：" + orderId));
			// 商户号
			packageParams.add(new BasicNameValuePair("mch_id", PayConfig.WEIXIN_MCH_ID));
			// 随机字符串
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			// 通知地址,接收微信支付异步通知回调地址
			packageParams.add(new BasicNameValuePair("notify_url", PayConfig.WEIXIN_NOTIFY_URL));
			// 商户订单号
			packageParams.add(new BasicNameValuePair("out_trade_no", orderId));
			// 终端IP,APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
			packageParams.add(new BasicNameValuePair("spbill_create_ip", "127.0.0.1"));
			// 总金额,订单总金额，只能为整数
			packageParams.add(new BasicNameValuePair("total_fee", price));
			// 交易类型,取值如下：JSAPI，NATIVE，APP，WAP
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));

			String sign = Util.genAppSign(packageParams);
			// 签名
			packageParams.add(new BasicNameValuePair("sign", sign));

			String xmlstring = Util.toXml(packageParams);
			return new String(xmlstring.toString().getBytes(), "ISO8859-1");

		} catch (Exception e) {
			Log.e(TAG, "genProductArgs fail, ex = " + e.getMessage());
			callback.onError(PayConfig.PAY_EXCEPTION);
			return null;
		}

	}

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals(WEIXIN_PAY_ACTION)) {
				int code = intent.getIntExtra("code", -100);
				if (code == 0) {
					callback.onSucced();
				} else {
					callback.onError(code);
				}
				unRegister();
			}
		}
	};

	private void onRegister() {
		IntentFilter inFilter = new IntentFilter(WEIXIN_PAY_ACTION);
		mContext.registerReceiver(mReceiver, inFilter);
	}

	private void unRegister() {
		mContext.unregisterReceiver(mReceiver);
	}
}
